<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/5/27
 * Time: 13:57
 */
namespace Modules\Api\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Collect;
use App\Models\Goods;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CollectController extends Controller{

    //收藏/取消收藏
    public function collectAdd(Request $request){
        try{
            $openid = $request->input("openid",false);
            $goodsid = $request->input("goods_id",false);
            if (!$openid || !$goodsid)return self::error(1000);
            //查询用户
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            $goods = Goods::find($goodsid);
            if (!$goods)return self::error(1005);
            $collect = Collect::where("userid",$user->id)->where("goods_id",$goods->id)->first();
            if (!$collect) {
                //加入收藏
                $collect = new Collect();
                $collect->userid = $user->id;
                $collect->goods_id = $goods->id;
                $collect->created_at = Carbon::now();
                $collect->save();
            }else{
                //取消收藏
                $collect->delete();
            }
            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //收藏列表
    public function collectList(Request $request){
        try{
            $openid = $request->input("openid",false);
            if (!$openid)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            $collect = Collect::where("userid",$user->id)->with("goods")->orderBy("id","desc")->get();
            return self::success($collect);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }
}